package com.lxp.base.net.okhttp.response;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.lxp.base.net.self.BaseCallBack;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by lxp on 2017/6/4.
 */

public abstract class GsonResponseHandler<T> implements BaseCallBack<T> {

    Type mType;
    Gson gson = new Gson();

    public GsonResponseHandler() {
        Type myclass = getClass().getGenericSuperclass();    //反射获取带泛型的class
        if (myclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameter = (ParameterizedType) myclass;      //获取所有泛型
        mType = $Gson$Types.canonicalize(parameter.getActualTypeArguments()[0]);  //将泛型转为type
    }

    public final Type getType() {
        return mType;
    }

    public abstract void onSuccess(String data, T obj);

    @Override
    public void isSuccess(String responseBodyStr, T t) {
        try {
            onSuccess(responseBodyStr, (T) gson.fromJson(responseBodyStr, getType()));
        } catch (Exception e) {
            isFail(e);
        }
    }

    @Override
    public void progress(double percent, long bytesRead, long contentLength, boolean done) {

    }
}
